import { useState, useCallback, useEffect } from 'react';
import { fetchOption, GetBigTablePieItems } from '@/services/commCRUD';
import _ from 'lodash';

export default () => {
  const [optionDatas, setOptionData] = useState<Map<string, API.OptionItem[]>>(
    new Map<string, API.OptionItem[]>(),
  );
  const [pieItems, setPieItems] = useState<Record<string, string[]>>();
  const [cascaderKeys, setCascaderKeys] = useState<Map<string, object>>(new Map<string, object>());
  const convertData = useCallback(
    (data: object[], optionTpl: string, valueTpl: string, parentTpl?: string) => {
      if (_.isEmpty(data)) {
        return;
      }
      const pData = {};
      data.map((l, i) => {
        let pNode = l[parentTpl!];
        if (_.isEmpty(pNode)) {
          pNode = 'top-node';
        }
        if (!pData[pNode]) {
          pData[pNode] = [];
        }
        pData[pNode].push(i);
      });
      const cascKeys = {};
      const createTreeData = (t: any[], p: any, keys: any[]) => {
        if (!pData[p]) {
          return;
        }
        pData[p].map((i: number) => {
          const id = data[i][valueTpl];
          const node = { value: id, label: data[i][optionTpl], key: id, children: [] };
          let thisKeys = [];
          if (keys) {
            thisKeys = keys.concat();
          }
          thisKeys.push(id);
          if (pData[id]) {
            createTreeData(node.children, id, thisKeys);
          }
          cascKeys[id] = thisKeys;
          t.push(node);
        });
        return t;
      };
      const treeData = createTreeData([], 'top-node', []);
      const d2 = { optionData: treeData as API.OptionItem[], cascaderKey: cascKeys as object };
      return d2;
    },
    [],
  );
  useEffect(() => {
    GetBigTablePieItems()
      .then(function (data) {
        setPieItems(data);
        return data;
      })
      .catch(function (ex) {
        console.error('请求宽表字段分析项目错误', ex);
      });
  }, []);
  const getOptionData = useCallback(
    (
      daoName: string,
      optionTpl: string,
      valueTpl: string,
      where: string,
      parentTpl?: string,
      sorter?: API.OrderItem[],
    ) => {
      const wStr = where ? where : '';
      const key = daoName + wStr;
      const data = optionDatas?.get(key);
      const cKeys = cascaderKeys?.get(key);
      if (_.isEmpty(data)) {
        const getOption = async (dao: string, wh: string) => {
          try {
            const ret = await fetchOption(dao, wh, sorter ? sorter : []);
            const d2 = convertData(ret, optionTpl, valueTpl, parentTpl);
            const ods = optionDatas;
            ods?.set(key, d2!.optionData);
            setOptionData(ods);
            const cks = cascaderKeys;
            cks.set(key, d2!.cascaderKey);
            setCascaderKeys(cks);
            return { optionDatas: d2!.optionData, cascaderKeys: d2!.cascaderKey };
          } catch (error) {
            console.error('请求', daoName, '数据', error);
          }
          return { optionDatas: undefined, cascaderKeys: undefined };
        };
        return getOption(daoName, where);
      }
      return { optionDatas: data, cascaderKeys: cKeys };
    },
    [optionDatas, cascaderKeys, convertData],
  );
  const getCascaderKeys = useCallback(
    (daoName: string, where: string) => {
      const wStr = where ? where : '';
      const key = daoName + wStr + '_cascader';
      return cascaderKeys?.get(key);
    },
    [cascaderKeys],
  );
  return {
    pieItems,
    optionDatas,
    cascaderKeys,
    getOptionData,
    getCascaderKeys,
  };
};
